namespace MapsTest.TestClasses
{
    using System;
    using Brjnk.Maps;

    /// <summary>
    /// </summary>
    public class TestTimer : ITimer
    {
        private TestTimingProvider provider;

        public TestTimer(TestTimingProvider provider)
        {
            this.provider = provider;
        }

        private long next;
        private long period;

        public event Action Elapsed;

        public void Change(long dueTime, long period)
        {
            if (dueTime < 0)
            { next = -1; period = -1; }

            next = provider.GetTime().Ticks + dueTime;
            if (period < 0)
            {
                this.period = long.MaxValue;
            }
            else
            {
                this.period = period;
            }
        }

        public void SetTime(TicksTime oldTime, TicksTime newTime)
        {
            if (next > oldTime.Ticks && next <= newTime.Ticks)
            {
                var count = (newTime.Ticks - next) / period + 1;
                if (Elapsed != null)
                {
                    for (int i = 0; i < count; i++)
                        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => Elapsed()));
                }
                next += period * count;
            }
        }
    }
}